package ServerSide;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import javax.swing.JTextArea;


/**
 * @author Avishai Kopeliansky 
 * @ID 066717752
 * @author David Shimshon
 * @ID 038185617
 */
public class Server extends Thread {
	private ServerSocket ssocket;
	private Socket socket;
	private boolean flag = true;
	private ClientHandling ch;
	JTextArea jta;
	
	/**
	 * Constructor
	 * @param jta TextArea
	 */
	public Server(JTextArea jta){
		this.ch = new ClientHandling(jta);
		this.jta = jta;
		
	}
	
	public void run(){
		try {
			this.flag = true;
			this.ssocket = new ServerSocket(9999);
			this.ssocket.setSoTimeout(100);
			while(this.flag){
				try {			
					
					this.socket = this.ssocket.accept();					
					this.ch.tempAdd(socket);
					this.jta.setCaretPosition(jta.getDocument().getLength());
				}
				catch (SocketTimeoutException e){
					if(this.ch.getFlag()){
						this.ch.checkAlive();
					}
				}
			
				catch (SocketException e)
				{}
			}
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Dispatch a system message
	 * @param s the message
	 */
	public void systemMsg(String s){
		String t = "<smsg>"+"<$System:"+s+">";
		ch.sysMsg(t);
	}
	/**
	 * Shutdown the Server in an orderly fashion 
	 */
	public void shutDown(){
		try{
			this.flag = false;
			this.ch.shutDown();
			while(this.ch.getFlag()){};
			this.ssocket.close();			
		}
		catch ( IOException e){
			e.printStackTrace();
		}
	}
	

}
